/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.common.core.decorator;

import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 上下文复制修饰
 * @author zhanghongyi
 * @date 2024/9/3
 * @description ContextCopyingDecorator
 */
public class ContextCopyingDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        try {
            //获取父线程的context
            RequestAttributes context = RequestContextHolder.currentRequestAttributes();
            return () -> {
                try {
                    //将父线程的context设置进子线程里
                    RequestContextHolder.setRequestAttributes(context);
                    //子线程方法执行
                    runnable.run();
                } finally {
                    //清除子线程context
                    RequestContextHolder.resetRequestAttributes();
                }
            };
        } catch (IllegalStateException e) {
            return runnable;
        }
    }
}
